package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"mishop/entitys"
	"mishop/models"
	"mishop/services"
	"mishop/utils"
	"strconv"
)

type IOrder interface {
	All(ctx *gin.Context)
	Show(ctx *gin.Context)
	Store(ctx *gin.Context)
	Update(ctx *gin.Context)
	Delete(ctx *gin.Context)
}
type Order struct {
	service services.IOrderService
}

func (c *Order) All(ctx *gin.Context) {
	pageEntity := entitys.PageEntity{}
	err := ctx.ShouldBindWith(&pageEntity, binding.JSON)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}

	userID := 0
	user_id := ctx.Query("user_id")
	if user_id != "" {
		parseInt, err := strconv.Atoi(user_id)
		utils.HandleErrors(err, ctx, 400, 1, "")
		if err != nil {
			return
		}
		userID = parseInt
	} else {
		utils.HandleErrors(err, ctx, 400, 1, "参数不正确")
		return
	}
	pages, err := c.service.FindByUserID(pageEntity.Page, pageEntity.Rows, uint(userID))
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 200, 0, "", pages)
}

func (c *Order) Show(ctx *gin.Context) {
	address_id := ctx.Param("address_id")
	addressID, err := strconv.Atoi(address_id)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}

	address, err := c.service.FindByID(uint(addressID))
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}

	utils.HandleSucess(ctx, 200, 0, "", address)
}

func (c *Order) Store(ctx *gin.Context) {

	orderEntity := models.Order{}
	err := ctx.ShouldBindWith(&orderEntity, binding.JSON)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	order, err := c.service.Create(&orderEntity)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 201, 0, "", order)

}

func (c *Order) Update(ctx *gin.Context) {

}

func (c *Order) Delete(ctx *gin.Context) {
	address_id := ctx.Param("address_id")
	addressID, err := strconv.Atoi(address_id)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	err = c.service.Delete(addressID)
	utils.HandleErrors(err, ctx, 400, 1, "")
	if err != nil {
		return
	}
	utils.HandleSucess(ctx, 200, 0, "删除成功", nil)

}

func NewOrder() IOrder {
	service := services.NewOrderService(
		models.NewOrder(models.Db),
		models.NewOrderItem(models.Db),
		models.NewProduct(models.Db),
	)
	return &Order{service: service}
}
